package com.think.admin.web.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.think.admin.cons.AdminCons;
import com.think.admin.model.dto.user.SysUserDTO;
import com.think.admin.model.param.user.SetUserRoleParam;
import com.think.admin.model.param.user.SysUserParam;
import com.think.admin.model.query.SysUserQuery;
import com.think.admin.oauth.util.OAuthUtil;
import com.think.admin.web.mapper.SysUserMapper;
import com.think.admin.web.service.ISysUserService;
import com.think.admin.web.service.IUserRoleService;
import com.think.admin.web.service.IUserService;
import com.think.common.enums.IsDeleteEnum;
import com.think.common.enums.StateEnum;
import com.think.common.enums.SysUserTypeEnum;
import com.think.common.exception.SysException;
import com.think.common.param.UpdateBatchParam;
import com.think.common.utils.ResultUtil;
import com.think.common.utils.SysUtils;
import com.think.common.web.service.impl.SuperServiceImpl;
import com.think.dao.entity.SysUser;
import com.think.dao.entity.User;
import com.think.dao.entity.UserRole;
import com.think.dao.enums.UserTypeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 管理员用户表 服务实现类
 * </p>
 *
 * @author xwj
 * @since 2019-04-08
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = SysException.class)
public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private final IUserService userService;
    private final IUserRoleService userRoleService;

    @Override
    public HttpEntity pageSysUser(Page<SysUserDTO> page, SysUserQuery sysUserQuery) {
        // 排除超级管理员，本身
        List<String> ruleOutIdList = new ArrayList<>();
        ruleOutIdList.add(AdminCons.Param.SUPER_ADMIN_ID);
        ruleOutIdList.add(OAuthUtil.getUserId());

        //查询自己的下级(超级管理员查看全部。老板查看本公司，其他查看自己创建的账号)
        if(!AdminCons.Param.SUPER_ADMIN_ID.equals(OAuthUtil.getUserId())){
            if (SysUtils.isNotEmpty(OAuthUtil.getUser().getType( ).getValue())){
                if (!AdminCons.SysUserParam.SUPER_ADMIN.equals(OAuthUtil.getUser().getType().getValue())){
                    sysUserQuery.setCreateUser(OAuthUtil.getUserId());
                }
                sysUserQuery.setType(OAuthUtil.getUser().getType());
            }
        }

        // 查询
        List<SysUserDTO> adminUserDTOList = baseMapper.selectPageSysUser(page, ruleOutIdList, sysUserQuery,
                StateEnum.ENABLE, IsDeleteEnum.NORMAL);

        // 返回
        return ResultUtil.success(page.setRecords(adminUserDTOList));
    }

    @Override
    public HttpEntity createOrUpdate(SysUserParam sysUserParam) {
        // 提取ID
        String userId = sysUserParam.getUserId();

        // 查重，账号唯一
        int usernameCount = this.lambdaQuery()
                .eq(SysUser::getUsername, sysUserParam.getUsername())
                .ne(SysUtils.isNotEmpty(userId), SysUser::getUserId, userId).count();
        if (0 != usernameCount) {
            throw new SysException("账号已存在，请重试");
        }

        // 查重，昵称唯一
        int nickNameCount = this.lambdaQuery()
                .eq(SysUser::getName, sysUserParam.getName())
                .ne(SysUtils.isNotEmpty(userId), SysUser::getUserId, userId).count();
        if (0 != nickNameCount) {
            throw new SysException("昵称已存在，请重试");
        }

        // sysUserParam 转换为 SysUser
        SysUser sysUser = sysUserParam.convert(SysUser.class);

        // 加密方式
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        // 初始化密码
        sysUser.setPwd(bCryptPasswordEncoder.encode(AdminCons.Param.DEFAULT_PASSWORD));

        //新增的时候，创建人的信息录入
        if(SysUtils.isEmpty(userId)){
            sysUser.setCreateUser(OAuthUtil.getUserId());
        }

        // 创建user
        if (SysUtils.isEmpty(userId)) {
            User user = new User();
            user.setUserType(UserTypeEnum.ADMIN);
            if (!userService.save(user)) {
                throw new SysException("user 新增失败");
            }
            sysUser.setUserId(user.getId());
        }

        // 新增或者修改系统用户信息
        if (!this.saveOrUpdate(sysUser)) {
            throw new SysException("新增或者修改系统用户信息失败");
        }

        // 新增或者修改用户角色
        userRoleService.lambdaUpdate().eq(UserRole::getUserId, sysUser.getUserId()).remove();
        if (SysUtils.isNotEmpty(sysUserParam.getRoleIdList())) {
            List<UserRole> userRoleList = new ArrayList<>();
            sysUserParam.getRoleIdList().forEach(roleId -> {
                UserRole userRole = new UserRole();
                userRole.setUserId(sysUser.getUserId());
                userRole.setRoleId(roleId);
                userRoleList.add(userRole);
            });
            if (!userRoleService.saveBatch(userRoleList)) {
                throw new SysException("新增或者修改用户角色信息失败");
            }
        }

        // 重建用户角色缓存
        userRoleService.resetUserRole();

        // 返回
        return ResultUtil.success();
    }

    @Override
    public HttpEntity delete(List<String> idList) {
        // 非空判断
        if (SysUtils.isEmpty(idList)) {
            return ResultUtil.requestParamError();
        }

        // 删除
        boolean deleteSuccess = this.lambdaUpdate()
                .set(SysUser::getIsDelete, IsDeleteEnum.DELETE)
                .set(SysUser::getGmtDelete, LocalDateTime.now())
                .in(SysUser::getUserId, idList)
                .update();
        if (deleteSuccess) {
            // 删除用户角色关联
            userRoleService.lambdaUpdate().in(UserRole::getUserId, idList).remove();

            // 重建用户角色缓存
            userRoleService.resetUserRole();

            // 返回
            return ResultUtil.deleteSuccess();
        } else {
            return ResultUtil.deleteError();
        }
    }

    @Override
    public HttpEntity updateState(UpdateBatchParam updateBatchParam) {
        // 非空判断
        if (SysUtils.isEmpty(updateBatchParam)) {
            return ResultUtil.requestParamError();
        }

        // 参数提取，非空判断
        StateEnum state = updateBatchParam.getState();
        List<String> idList = updateBatchParam.getIdList();
        if (SysUtils.isNull(state, idList)) {
            return ResultUtil.requestParamError();
        }

        // 更新
        boolean updateIsSuccess = this.lambdaUpdate()
                .in(SysUser::getUserId, idList)
                .update(new SysUser().setState(state));
        if (updateIsSuccess) {
            return ResultUtil.success();
        } else {
            return ResultUtil.updateError();
        }
    }

    @Override
    public HttpEntity resetPwd(List<String> idList) {
        // 非空判断
        if (SysUtils.isEmpty(idList)) {
            return ResultUtil.requestParamError();
        }

        // 加密方式
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        // 更新
        boolean updateIsSuccess = this.lambdaUpdate()
                .in(SysUser::getUserId, idList)
                .update(new SysUser().setPwd(bCryptPasswordEncoder.encode(AdminCons.Param.DEFAULT_PASSWORD)));
        if (updateIsSuccess) {
            return ResultUtil.success();
        } else {
            return ResultUtil.updateError();
        }
    }

    @Override
    public HttpEntity setUserRole(SetUserRoleParam setUserRoleParam) {
        // 非空判断
        if (SysUtils.isEmpty(setUserRoleParam)) {
            return ResultUtil.requestParamError();
        }

        // 参数提取，非空判断
        List<String> userIdList = setUserRoleParam.getUserIdList();
        List<String> roleIdList = setUserRoleParam.getRoleIdList();
        if (SysUtils.isNull(userIdList)) {
            return ResultUtil.requestParamError();
        }

        // 删除
        userRoleService.lambdaUpdate().in(UserRole::getUserId, userIdList).remove();

        // 用户ID列表为空，直接返回
        if (SysUtils.isEmpty(roleIdList)) {
            // 重建用户角色缓存
            userRoleService.resetUserRole();
            return ResultUtil.success();
        }

        // 重建用户角色关联
        List<UserRole> userRoleList = new ArrayList<>();
        userIdList.forEach(userId -> roleIdList.forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        }));
        if (true == userRoleService.saveBatch(userRoleList)) {
            // 重建用户角色缓存
            userRoleService.resetUserRole();
            return ResultUtil.success();
        } else {
            throw new SysException("重建用户角色关联失败");
        }
    }

    /**
     * <p>
     * 销售人员查看
     * </p>
     * @author CaiWenYi
     * @Date: 2019/7/14 12:10
    */
    @Override
    public HttpEntity pageSysUserSelectList(Page<SysUserDTO> page, SysUserQuery sysUserQuery){

        try {
            //超级管理员能查看全村人
            //if(!AdminCons.Param.SUPER_ADMIN_ID.equals(OAuthUtil.getUserId())){
            //    sysUserQuery.setCreateUser(OAuthUtil.getUserId());
            //    sysUserQuery.setCompanyId(OAuthUtil.getUser().getCompanyId());
            //}

            //必须是销售人员，是启用状态的
            sysUserQuery.setType(SysUserTypeEnum.SALESCHANNEL);
            sysUserQuery.setState(StateEnum.ENABLE);
            sysUserQuery.setIsDelete(IsDeleteEnum.NORMAL);

            // 查询
            List<SysUserDTO> adminUserDTOList = baseMapper.selectPageSysUserSelectList(page, sysUserQuery);

            // 返回
            return ResultUtil.success(page.setRecords(adminUserDTOList));
        }catch (Exception E){
            E.printStackTrace();

        }
        return ResultUtil.success();
    }
}
